--region NewFile_1.lua
--Author : zhoujibo
--Date   : 2015/5/25
--此文件由[BabeLua]插件自动生成

module('UBBStylePlugin',package.seeall)


require "template/text_style_tpl"

SCHEME_GETSIZE_DICT = {}
SCHEME_GETOBJ_DICT = {}

TAG_CONVERT_DICT = {}
STYLESHEET = {}

PROTECTED_TAGS = {}
MUST_CUSTOM_DEFINE_TAGS = {}


function registerScheme(scheme,getSizeFunc,getObjectFunc)
    SCHEME_GETSIZE_DICT[scheme] = getSizeFunc
    SCHEME_GETOBJ_DICT[scheme] = getObjectFunc
end

function registerTagConvert(tag,func)
    TAG_CONVERT_DICT[tag] = func
end

function getStyle(name,customTag)
    local visited = {}
    while true do
        name =(name=='' and 'c')or name
        local style =(customTag and customTag[name])
        --要么是非c标签，要么有值(c标签一定要在customTag里面有值)
        assert(name~='c' or style,'no default custom tag!')
        style = style or STYLESHEET[name] or STYLESHEET.unknown
        if visited[style] then
            assert('circle reference definition in tags!'..name)
        elseif style.type == 'ref' then
            name = style.name
            visited[style] = true
        else
            return style
        end
    end
end


function _getImgSize(url,params,sX,sY)
    local charWidth,charHeight

    assert(url~=nil,'must have pic Path in UBBLabel element of image type')
    local frame = cc.SpriteFrameCache:getInstance():getSpriteFrame(url)
    --assert(frame~=nil,'no valid picture!')
    if frame then
        local size = frame:getRect()
        charWidth = size.width*sX
        charHeight = size.height*sY
    else
        charWidth = 40*sX
        charHeight = 40*sY
    end    
    return charWidth,charHeight
end


function _getImgObj(url,params,sX,sY,oldObj,oldObjUrl)
    local sp
    _setSpriteFrameForImg(url)
    if oldObj then
        sp = oldObj
        if oldObjUrl ~= url then
            sp:setSpriteFrame(url)
        end
    else
        sp = cc.Sprite:createWithSpriteFrameName(url)
    end
    sp:setScaleX(sX)
    sp:setScaleY(sY)
    return sp
end

_DEFAULT_SPRITEFRAME = nil
function _setSpriteFrameForImg(path)
    if not cc.SpriteFrameCache:getInstance():getSpriteFrame(path)then
        if not _DEFAULT_SPRITEFRAME then
            local dn = cc.DrawNode:create()
            local ox = 0
            local oy = 0
            local h = 40
            local w = 40
            local vList = {cc.p(ox,oy),cc.p(ox,h+oy),cc.p(w+ox,h+oy),cc.p(w+ox,oy),cc.p(ox,oy)}
            local colors = {cc.c4f(0.3,0.3,0.3,1),cc.c4f(0.7,0.7,0.7,1),cc.c4f(0.6,0.6,0.6,1),cc.c4f(0.2,0.2,0.2,1)}--左下右上
            for i = 1,4 do
                dn:drawSegment(vList[i],vList[i+1],1,colors[i])
            end
	        local renderTexture = cc.RenderTexture:create(40,40)
            renderTexture:begin()
	        dn:visit()
	        renderTexture:endToLua()
            local tex = renderTexture:getSprite():getTexture()       
            _DEFAULT_SPRITEFRAME = cc.SpriteFrame:createWithTexture(tex,{x=0,y=0,width=tex:getPixelsWide(),height=tex:getPixelsHigh()})
        end
        cc.SpriteFrameCache:getInstance():addSpriteFrame(_DEFAULT_SPRITEFRAME,path)
    end
end


function _convertCountTag(params,url)
    local style = params[1]
    local result = {}
    for i = 1,string.len(url)do
        local c = string.sub(url,i,i)
        if c== '/' then c= 'slash' end
        table.insert(result,string.format('[img]res/public/digit%s/img_%s.png[/img]',style,c))
    end
    return '[g]'..table.concat(result)..'[/g]'
end

function _convertVIPTag(params,url)
    return string.format('[img]res/public/icon/img_vip%s.png[/img]',url)
end

function _convertBigNumber(params,url)
    local number = math.floor(tonumber(url))
    if number>=1000000 then
        number =  string.format("%.1f", number/1000000)..'M'
    elseif number>=10000 then
        number =  string.format("%.1f", number/10000)..'w'
    elseif number>=1000 then
        number =  string.format("%.1f", number/1000)..'k'
    end
    return tostring(number)
end

function _addProtectedTags(tagName,tag)
    STYLESHEET[tagName] = tag
    PROTECTED_TAGS[tagName] = true
end

function _addMustCustomDefineTags(tagName,tag)
    STYLESHEET[tagName] = tag
    MUST_CUSTOM_DEFINE_TAGS[tagName] = true
end


function _builtinSetup()
    --内置对img的处理
    registerScheme('img',_getImgSize,_getImgObj)
    --内置count的转换
    registerTagConvert('count',_convertCountTag)
    registerTagConvert('vip',_convertVIPTag)
    registerTagConvert('bignumber',_convertBigNumber)

    --内置的tag，不能被复写
    _addProtectedTags('text',{type='text'})
    _addProtectedTags('img',{type='res',scheme='img'})
    _addProtectedTags('s',{type='scale'})
    _addProtectedTags('touch',{type='touch'})
    _addProtectedTags('p',{type='para'})
    _addProtectedTags('g',{type='group'})
    _addProtectedTags('la',{type='linealign'})
    _addProtectedTags('unknown',{type='res',scheme='img',url='unknown'})
    _addProtectedTags(' ')
    _addProtectedTags('c')

    --必须要有定义的tag
    _addMustCustomDefineTags('star',{type='res',scheme='img',url='res/public/icon/btn_star_normal.png'})
    _addMustCustomDefineTags('li',{type='li',ref='star'})
    _addMustCustomDefineTags('default',{type='text',color=0xffffffff,fontsize=20,
    outline=0,outlineColor=0xFFFFFFFF,font=DEFAULT_TTF_PATH})
end


function _tplSetup()

    --暂时自己弄，等datamanager整理好后再整理  zjb 2015年5月14日
    
    local function tpl2dic(tpl)
        local dict = {}
        local keys,values = unpack(tpl)
        for i,key in pairs(keys)do
            dict[key] = values[i]
        end
        return dict
    end
    local function arr2dic(arr)
        local dict = {}
        for _,item in pairs(arr)do
            dict[item[1]] = item[2]
        end
        return dict
    end

    local function selectRequirePathByName(s_name)
        -- require("template/"..s_name)
        if not DEBUG_VERSION then
            require("template/"..s_name)
            return
        end
        local down = DownLoadFile:getInstance()
        if down:downLoadFileMainThread(DEBUG_TPL_HOST_IP,s_name,"lua")then
            require(s_name)
        else
            print('add from local')
            require("template/"..s_name)
            --assert(false,'not downloaded!')
        end
        assert(text_style_tpl,'no tpl')
    end
    selectRequirePathByName('text_style_tpl')
    --([1] = {[1] = "default",[2] = {[1] = {[1] = "type",[2] = "text",},[2] = {[1] = "frontsize",[2] = 18,},...},[2]=...}

    local sheetDict = {}
    for _,arr in pairs(text_style_tpl[2][1])do
        sheetDict[arr[1]] = arr2dic(arr[2])
    end
    --{["s7"] = {[1] = {[1] = "type",[2] = "text",},[2] = {[1] = "frontsize",[2] = 18,},[3] = {[1] = "color",[2] = "0xff409ace",},},
    for key,arr in pairs(sheetDict.text_style)do
        sheetDict[string.sub(key,2)] = arr2dic(arr)
    end
    sheetDict.text_style = nil

    --处理16进制数字转换
    local reversedTags = {}
    for _,key in pairs({" ","c","img","text","g","touch","s","p","la"})do 
        reversedTags[key] = true
    end
    for key,style in pairs(sheetDict)do
        key = string.lower(key)
        assert(not PROTECTED_TAGS[key],'set illegal tag!'..key)
        STYLESHEET[key] = style
        MUST_CUSTOM_DEFINE_TAGS[key] = nil
        print('add style '..key)
        if style.color then
            style.color = tonumber(style.color)
        end
        if style.outlineColor then
            style.outlineColor = tonumber(style.outlineColor)
        end
    end
    for key in pairs(MUST_CUSTOM_DEFINE_TAGS)do
        assert(false,key..' not defined!')
    end
end

_INITED = _INITED or false
if not _INITED then
    _INITED = true
    _builtinSetup()
    _tplSetup()
end


--endregion



--endregion
